package cn.zbmao.web.controller.user;

import cn.zbmao.web.bean.User;
import cn.zbmao.web.interceptor.user.UserIntercepter;
import cn.zbmao.web.util.DateUtil;
import cn.zbmao.web.util.StringOperateUtil;
import cn.zbmao.web.util.dao.DaoFactory;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;

import java.util.List;

public class KeywordController extends Controller {

    /**
     * 添加关键字
     */
	@Before(UserIntercepter.class)
	public void add(){
		String key = getPara("key");

        key= Jsoup.clean(StringOperateUtil.exChange(key),Whitelist.basic());
        String [] str=StringOperateUtil.reString(key).trim().split(" ");

        User user = (User)getSessionAttr("user");
		List<Record> list = DaoFactory.getUserDao().findUser_keyword(user.getInt("id"));
        //判断用户关注关键字长度不得超过5个
        if(list.size()+str.length>5){
            setAttr("msg",2);
            render(new JsonRender().forIE());
            return;
        }else {
            //用户关注的关键字不得为空
           for(String st:str) {
           if (StringUtils.isBlank(st)) {
               setAttr("msg", 3);

               render(new JsonRender().forIE());
               return;
//               判断用户关注关键字是否存在
           } else if (list.contains(new Record().set("keyword", st))) {
               setAttr("msg", 0);
               render(new JsonRender().forIE());
               return;
           }
       }
                for(String st:str) {
                if (DaoFactory.getUserDao().addUser_keyword(st, user.getInt("id"))) {
                    DaoFactory.getUserDao().addUser_keyword_log(st, user.getInt("id"), DateUtil.getNowToInt());
                }
                setAttr("msg", 1);

            }

		}
		//關鍵字設置限制模塊
//		int size = DaoFactory.getUserDao().findUser_keyword_log(user.getInt("id"),DateUtil.getNowToInt()-3600*24);
	
//		if (size<10) {
//			关键字设置次数限制
//		}else{
//			
//			setAttr("msg", 3);
//		}
		render(new JsonRender().forIE());
	}

    /**
     * 删除关键字
     */
	@Before(UserIntercepter.class)
	public void delete(){
		DaoFactory.getUserDao().deleteUser_keyword(getParaToInt());
		redirect("/news/condition");
	}


}
